<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<jk-button type="primary" size="mini" icon="el-icon-c-scale-to-original" :disabled="!checkData || !checkData.length" @click="onBatchEditBtn">批量配置</jk-button>
				</div>
				<div class="flex-end-center-wrap">
					<el-checkbox v-model="isCustomDate" border class="item-gap" size="small">自定义</el-checkbox>
					<el-radio-group v-if="!isCustomDate" v-model="dateType" size="small" class="item-gap" @change="onDateTypeChange">
						<el-radio-button
							v-for="(dateTypeItem) in dateTypeList"
							:key="dateTypeItem.id"
							:label="dateTypeItem.id"
						>{{ dateTypeItem.name }}</el-radio-button>
					</el-radio-group>
					<jk-date-picker v-else v-model="searchParams.belongDate" type="datetimerange" :clearable="true" start-placeholder="计划开始日期" end-placeholder="计划结束日期" class=" margin-5-0 item-gap"></jk-date-picker>
					<!--<el-radio-group v-model="searchParams.upkeepTypeId" size="small" class="item-gap">
						<el-radio-button
							v-for="(dateTypeItem) in upkeepTypeList"
							:key="dateTypeItem.id"
							:label="dateTypeItem.id"
						>{{ dateTypeItem.name }}</el-radio-button>
					</el-radio-group>-->
					<jk-select v-model="searchParams.upkeepTypeId" :clearable="true" :option-list="upkeepTypeList" placeholder="保养类别" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-select v-model="searchParams.workshopId" :clearable="true" :option-list="workshopList" placeholder="区域" class="search-bar-item-size1 margin-5-0 item-gap"></jk-select>
					<jk-search-input v-model="searchParams.machineNameOrCode" placeholder="设备编号或名称" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-input v-model="searchParams.upkeepItemName" placeholder="保养项目" size="small" class="search-bar-item-size2 margin-5-0 item-gap" clearable @on-enter="onSearchBtn" />
					<jk-search-button @click="onSearchBtn"></jk-search-button>
				</div>
			</div>
		</jk-operation-card>

		<jk-card>
			<jk-table
				ref="jkTable"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 20"
				:checkbox-config="{strict: true}"
				@checkbox-change="onCheckboxChange"
			>
				<vxe-table-column fixed="left" type="checkbox" width="60" align="center"></vxe-table-column>
				<vxe-column
					v-for="(item, index) in tableColumnList"
					:key="index"
					:title="item.title"
					:align="item.align"
					:field="item.keyName"
					:sortable="item.sortable"
					:fixed="item.fixed ? item.fixed : ''"
					:min-width="item.minWidth"
					:width="item.width"
				>
					<template v-if="item.keyName === 'itemList'" #header>
						<div class="flex-start-center">
							<span class="margin-right-10">项目明细</span>
							<!--<div class="margin-right-10">
								<el-checkbox v-model="isSignIn" border size="mini" @change="onSignInChange">签到</el-checkbox>
							</div>
							<jk-button v-if="isSignIn" size="mini" type="primary" icon="el-icon-date" @click="onBatchConfirmBtn">确定签到 {{ isSignIn ? checkUpkeepData.length : '' }}个</jk-button>-->

							<div class="flex-start-center margin-left-10">
								<state-legend class="margin-right-10" :state-list="stateList"></state-legend>
							</div>
						</div>
					</template>
					<template slot-scope="scope">
						<jk-common-status v-if="item.keyName === 'auditState'" :status="scope.row.auditState"></jk-common-status>
						<span v-else-if="item.keyName === 'empName'">{{ scope.row.itemList && scope.row.itemList.length ? scope.row.itemList[0].empName : '' }}</span>
						<div v-else-if="item.keyName === 'itemCount'">{{ scope.row.itemList ? scope.row.itemList.length : '0' }}</div>
						<div v-else-if="item.keyName === 'itemList'" class="flex-start-center-wrap">
							<task-list
								:is-sign-in="isSignIn"
								:check-upkeep-data="checkUpkeepData"
								:item-list="scope.row.itemList"
								@change="onSelectUpkeepItem"
							></task-list>
						</div>
						<span v-else>{{ scope.row[item.keyName] }}</span>
					</template>
				</vxe-column>
				<vxe-column title="操作" align="center" fixed="right" :width="120">
					<template slot-scope="scope">
						<div>
							<el-button size="mini" type="primary" @click="onEditBtn(scope.row)">配置项目</el-button>
						</div>
					</template>
				</vxe-column>
			</jk-table>

			<!-- 分页组件 -->
			<footer ref="box2" class="flex-end-center margin-top-10">
				<jk-page
					:page-index="searchParams.pageNo"
					:page-sizes="searchParams.pageSizes"
					:page-size="searchParams.pageSize"
					:total="totalCount"
					@on-change="onPageChange"
				/>
			</footer>
		</jk-card>
		<save-dialog
			:data-id="dataId"
			:data-ids="dataIds"
			:dialog-state="saveDialogState"
			@on-visible-change="onVisibleChange"
			@on-finish="onFinish"
		></save-dialog>
		<batch-save-dialog
			:data-list="checkData"
			:dialog-state="batchSaveDialogState"
			@on-visible-change="onVisibleChangeOfBatchSaveDialog"
			@on-finish="onFinishOfBatchSaveDialog"
		></batch-save-dialog>
	</div>
</template>

<script>
    import { auditStateList } from '@/utils/jk/status-option-list';
    import saveDialog from './save-dialog';
    import batchSaveDialog from './batch-save-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import { pageConfig, tipsBar, formatTime, formatDate } from '/src/utils/jk/jk-tool';
    import getMenuColumn from '../../../../mixins/getMenuColumn';
    import handlerCache from '../../../../mixins/handler-cache';
    import { machineManagerUpkeepMachineJobMachinePage } from '../../../../api/machine/upkeepTask';
    import taskList from './components/task-list';
    import stateLegend from '../../../production/afterSpinPrdSchedulingCenter/components/state-legend';
    import { machineManagerUpkeepMachineJobBatchTaking } from '../../../../api/machine/machineUpkeepItemConfig';
    import { machineManagerUpkeepTypePage } from '../../../../api/machine/upkeepCategory';
    export default {
        name: 'MachineUpkeepItemConfig',
        components: {
            batchSaveDialog,
            stateLegend,
            taskList,
            saveDialog
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                prefix: 'workforcemanagement:upkeepMachineItem',
                apiItem: {
                    'page': machineManagerUpkeepMachineJobMachinePage
                },
                batchSaveDialogState: false,
                dateTypeList: [
                    { id: 14, name: '最近两周' },
                    { id: 7, name: '最近一周' },
                    { id: 1, name: '最近两天' },
                    { id: 0, name: '今天' },
                    { id: -1, name: '所有' }
                ],
                editType: null,
                workshopList: [],
                importDialogState: false,
                auditStateList: auditStateList,
                stateList: [
                    { id: 0, name: '计划中', color: '#5cadff' },
                    { id: 1, name: '到期', color: '#ff9900' },
                    { id: 2, name: '保养中', color: '#19be6b' }
                ],
                dataId: null,
                dataIds: [],
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                totalCount: 0,
                isCustomDate: false,
                dateType: -1,
                upkeepTypeList: [],
                searchParams: {
                    pageNo: 1,
                    pageSize: pageConfig.pageSize,
                    machineNameOrCode: '',
                    upkeepItemName: '',
                    upkeepTypeId: null,
                    belongDate: [],
                    stateList: [0, 1, 2]
                },
                checkData: [],
                isSignIn: false,
                checkUpkeepData: []
            };
        },
        methods: {
            onFinishOfBatchSaveDialog() {
                this.batchSaveDialogState = false;
                this.getListRequest();
            },
            onVisibleChangeOfBatchSaveDialog(e) {
                this.batchSaveDialogState = e;
            },
            onBatchConfirmBtn() {
                const ids = this.checkUpkeepData.map(x => x.id);
                if (ids.length) {
                    machineManagerUpkeepMachineJobBatchTaking({
                        ids: ids
                    }).then(res => {
                        if (res.data.status === 200) {
                            this.isSignIn = false;
                            tipsBar(this, 'save');
                            this.getListRequest();
                        }
                    });
                } else {
                    tipsBar(this, 'custom', 'warning', '请选择项目!');
                }
            },
            onDateTypeChange(e) {
                if (e === -1) {
                    this.$set(this.searchParams, 'belongDate', []);
                } else {
                    this.$set(this.searchParams, 'belongDate', [formatDate(Date.now() - (e * 24 * 60 * 60 * 1000)) + ' 00:00:00', formatDate(Date.now()) + ' 23:59:59']);
                }
            },
            onBatchEditBtn() {
                this.editType = 1;
                this.batchSaveDialogState = true;
            },
            onSignInChange(e) {
                if (!e) {
                    this.checkUpkeepData = [];
                }
            },
            onSelectUpkeepItem(e) {
                this.checkUpkeepData = e;
            },
            onCheckboxChange(e) {
                this.checkData = e.records ? e.records.map(x => {
                    return {
                        machineId: x.id,
                        machineCode: x.code,
                        machineName: x.name,
                        processId: x.processId,
                        processCode: x.processCode,
                        processName: x.processName,
                        workshopId: x.workshopId,
                        workshopCode: x.workshopCode,
                        workshopName: x.workshopName,
                        itemList: []
                    };
                }) : [];
            },
            onEditBtn(row) {
                this.dataId = row.id;
                this.dataIds = row.itemList.map(x => x.upkeepItemId);

                this.editType = 0;
                this.checkData = [{
                    machineId: row.id,
                    machineCode: row.code,
                    machineName: row.name,
                    processId: row.processId,
                    processCode: row.processCode,
                    processName: row.processName,
                    workshopId: row.workshopId,
                    workshopCode: row.workshopCode,
                    workshopName: row.workshopName,
                    itemList: row.itemList
                }];
                this.$refs.jkTable.$refs.xTable.clearCheckboxRow();
                this.saveDialogState = true;
            },
            onVisibleChangeOfImportDialog(e) {
                this.importDialogState = e;
            },
            onFinishBtnOfImportDialog() {
                this.importDialogState = false;
                this.getListRequest();
            },
            onPageChange(pageIndex, pageSize) {
                this.searchParams.pageNo = pageIndex;
                this.searchParams.pageSize = pageSize;
                this.getListRequest();
            },
            onFinish() {
                this.saveDialogState = false;
                this.getListRequest();
            },
            onVisibleChange(e) {
                if (!e) {
                    this.dataId = null;
                }
                this.saveDialogState = e;
            },
            /** 查询列表 */
            getListRequest() {
                this.checkData = [];
                this.checkUpkeepData = [];
                this.tableLoading = true;
                this.apiItem.page(this.searchParams).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res;
                        this.totalCount = res.data.count;
                    }
                });
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.totalCount = 1;
                this.getListRequest();
            },

            /** 删除按钮操作 */
            onDeleteBtn(row) {
                this.apiItem.delete({ id: row.id }).then((res) => {
                    if (res.data.status === 200) {
                        this.getListRequest();
                        this.$tipsBar(this, 'delete');
                    }
                }).catch(() => {});
            },
            clearCacheMethod() {
                // Object.assign(this.$data, this.$options.data());
                this.$nextTick(() => {
                    this.getDependentData();
                });
            },
            getUpkeepTypeListRequest() {
                return machineManagerUpkeepTypePage({ auditState: 1 }).then(res => {
                    if (res.data.status === 200) {
                        this.upkeepTypeList = res.data.res || [];
                    }
                });
            },
            async getDependentData() {
                this.onDateTypeChange(this.dateType);
                this.workshopList = this.$store.state.user.userWorkshop.workshopList;
                this.$set(this.searchParams, 'workshopId', this.$store.state.user.userWorkshop.defaultWorkshopId);
                await this.getUpkeepTypeListRequest();
                await this.getMenuColumnListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
